package com.iyundao.io.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iyundao.io.Service.SysUserService;
import com.iyundao.io.model.SysUser;
import com.iyundao.io.model.SysUserInfo;
import com.iyundao.io.tools.AesCbcUtil;
import com.iyundao.io.tools.HttpRequest;
import com.iyundao.io.tools.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/wechat")
public class WeChatController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserController userController;


    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public String code(String code){
        /*JSONObject object = JSONObject.parseObject(param);
        String code = (String) object.get("code");*/
        // login code can not be null
        if (code == null || code.length() == 0) {
            return "code不能为空";
        }
        // mini-Program's AppID
        String wechatAppId = "wxe1184bbaaedfd86b";

        // mini-Program's session-key
        String wechatSecretKey = "3442b30372d452fdce32943926fdfda1";

        String grantType = "authorization_code";

        // using login code to get sessionId and openId
        String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&js_code=" + code + "&grant_type=" + grantType;

        // sending request
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

        // analysis request content
        JSONObject json = JSONObject.parseObject(sr);

        // getting session_key
        String sessionKey = json.get("session_key").toString();

        // getting open_id
        String openId = json.get("openid").toString();

        return openId;
    }

    /**
     * decoding encrypted data to get openid
     * @return
     */
    @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
    public Map decodeUserInfo(@RequestBody String param) {
        JSONObject object = JSONObject.parseObject(param);
        String iv = (String) object.get("iv");
        String encryptedData = (String) object.get("encryptedData");
        String code = (String) object.get("code");
        Map map = new HashMap();
        // login code can not be null
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        // mini-Program's AppID
        String wechatAppId = "wxe1184bbaaedfd86b";

        // mini-Program's session-key
        String wechatSecretKey = "3442b30372d452fdce32943926fdfda1";

        String grantType = "authorization_code";

        // using login code to get sessionId and openId
        String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&js_code=" + code + "&grant_type=" + grantType;

        // sending request
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

        // analysis request content
        JSONObject json = JSONObject.parseObject(sr);

        // getting session_key
        String sessionKey = json.get("session_key").toString();

        // getting open_id
        String openId = json.get("openid").toString();

        // decoding encrypted info with AES
        try {
            String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = JSONObject.parseObject(result);
                Map userInfo = new HashMap();
                userInfo.put("openId", userInfoJSON.get("openId"));
                userInfo.put("nickName", userInfoJSON.get("nickName"));
                userInfo.put("gender", userInfoJSON.get("gender"));
                userInfo.put("city", userInfoJSON.get("city"));
                userInfo.put("province", userInfoJSON.get("province"));
                userInfo.put("country", userInfoJSON.get("country"));
                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                userInfo.put("unionId", userInfoJSON.get("unionId"));
                map.put("userInfo", userInfo);
                return map;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;
    }

    /**
     * 授权判断
     * @param param
     * @return
     */
    @RequestMapping(value = "/selectInfoByOpenid")
    public ResponseData selectInfoByOpenid(@RequestBody String param) {
        JSONObject object = JSONObject.parseObject(param);
        String openid = (String) object.get("openid");
        SysUserInfo sysUserInfo = null;
        sysUserInfo = sysUserService.selectInfoByOpenid(openid);
        if (sysUserInfo == null || sysUserInfo.equals("")) {
            return new ResponseData(0,"不存在");
        } else {

            if (sysUserInfo.getUid() == null || sysUserInfo.getUid().equals("")) {
                return new ResponseData(99,"游客");
            } else {
                SysUser sysUser = sysUserService.selectByOpenid(sysUserInfo.getOpenid());
                sysUser.setLoginPwd(sysUser.getLoginName());
                Object o = JSONObject.toJSON(sysUser);
                JSONObject params = JSONObject.parseObject(o.toString());

                return userController.searchUserInfo(params);
            }

        }
    }

    @RequestMapping(value = "/addsysuserinfo")
    public ResponseData addSysUserInfo(@RequestBody String param) {
        JSONObject object = JSONObject.parseObject(param);
        String phone = (String) object.get("phone");
        JSONObject sysUserInfo = (JSONObject)object.get("sysUserInfo");
        SysUserInfo sysUserInfo2 = JSON.toJavaObject(sysUserInfo, SysUserInfo.class);

        SysUser sysUser = null;
                sysUser =  sysUserService.selectByPhone(phone);
        if (sysUser != null && !sysUser.equals("")){
            sysUserInfo2.setUid(sysUser.getSid());
            SysUserInfo sysUserInfo1 = null;
            sysUserInfo1 = sysUserService.selectInfoByOpenid(sysUserInfo2.getOpenid());

            if (sysUserInfo1 == null || sysUserInfo1.equals("")) {
                sysUserService.addSysUserInfo(sysUserInfo2);
                sysUser.setLoginPwd(sysUser.getLoginName());
                Object o = JSONObject.toJSON(sysUser);
                JSONObject params = JSONObject.parseObject(o.toString());
                return userController.searchUserInfo(params);
            } else {
                int i = sysUserService.updateSysUserInfo(sysUser.getSid(), sysUserInfo2.getOpenid());
                if (i > 0) {
                    sysUser.setLoginPwd(sysUser.getLoginName());
                    Object o = JSONObject.toJSON(sysUser);
                    JSONObject params = JSONObject.parseObject(o.toString());
                    return userController.searchUserInfo(params);
                } else {
                    return new ResponseData(0,"手机号绑定失败");
                }
            }


        } else {
            SysUserInfo sysUserInfo1 = sysUserService.addSysUserInfo(sysUserInfo2);
            return new ResponseData(99,"游客",sysUserInfo1);
        }


    }
}
